﻿using Framework;

namespace Game
{
    public class SceneMonsterBehaviorComponent : IComponent
    {
        private SceneMonsterBTContext _context;
        private IBehaviorTree _behaviorTree;
        
        public SceneMonsterBehaviorComponent()
        {

        }
        
        public void Dispose()
        {
            if (_behaviorTree != null)
            {
                BTreeScheduler.Instance.StopTree(_behaviorTree);
            }
        }
        
        public void Setup(SceneMonsterEntity sceneMonster)
        {
            _context = new SceneMonsterBTContext();
            _context.sceneObject = sceneMonster;
            BTreeBuilder<SceneObjectBTContext> builder = new BTreeBuilder<SceneObjectBTContext>(_context);
            SceneObjectStateComposite stateComposite = new SceneObjectStateComposite();
            builder.BeginCustomComposite(stateComposite);
            builder.Actionable(new SceneObjectIdleActionable());
            builder.Actionable(new SceneObjectAttackActionable());
            builder.Actionable(new SceneObjectBeHitActionable());
            builder.Actionable(new SceneObjectDieActionable());
            builder.EndComposite();

            stateComposite.AddTransition(
                new SceneObjectDirectTransition(-1, SceneMonsterStates.Idle, 0));
            stateComposite.AddTransition(
                new SceneObjectFaceAndHitTransition(-1, SceneMonsterStates.Attack, 1));
            stateComposite.AddTransition(
                new SceneObjectBeHitTransition(-1, SceneMonsterStates.BeHit, 2));
            stateComposite.AddTransition(
                new SceneObjectDieTransition(-1, SceneMonsterStates.Die, 3));

            _behaviorTree = builder.Build();
            BTreeScheduler.Instance.StartTree(_behaviorTree); 
        }
        
        public void CollidedWith(SceneObjectEntity collidedEntity)
        {
            _context.collidedEntity = collidedEntity;
        }
        
        public void BeHit(SceneObjectEntity attackEntity)
        {
            _context.attackEntity = attackEntity;
        }
    }
}